﻿using DG.Tweening;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;


public class UIMatch : UIBase
{
    public Button buttonClose;
    public Button buttonEnterRoom;
    public Button buttonRandomRoom;
    public Button buttonCreateRoom;
    public Button buttonStartBattle;
    public Button buttonExitRoom;
    public Text textCotent;
    public InputField textRoomId;
    private Sequence _sequence;
    private const int MaxRoomNum = 8;
    protected override void Awake()
    {
        base.Awake();
        buttonStartBattle.gameObject.SetActive(false);
        buttonExitRoom.gameObject.SetActive(false);

        //登录，进入旧的房间
        ReEnterRoom();
    }
    public override void OnButtonCloseClick()
    {
        base.OnButtonCloseClick();
        SceneMgr.Instance.LoadScene(SceneName.SceneLogin);
    }

    private const int CreateRoomId = -1;
    private const int RandomMatchRoomId = -2;
    private bool _isRoomHost = false;
    public void OnEnterRoom(Button button)
    {
        _isRoomHost = false;
        string roomId;
        string roomIdStr = textRoomId.text.Trim();
        if (string.IsNullOrEmpty(roomIdStr))
        {
            UITips.Instance.Show(XLocalization.Get("请输入房号"));
            return;
        }
        roomId = roomIdStr;

        var req = new enterroom();
        req.group_id = roomId;
        WebSocketClient.Instance.SendSerialize(button, req);
        Clear();
    }

    public void OnCreateRoom(Button button)
    {
        WebSocketClient.Instance.SendMsgName(button, nameof(createroom));
        Clear();
    }

    public void OnRandomEnterRoom(Button button)
    {
        throw new System.Exception("public void OnRandomEnterRoom(Button button)");
    }

    public void OnButtonCopyRoomClick()
    {
#if UNITY_WEBGL
        UITips.Instance.Show("非常抱歉，当前平台权限出问题了。");
        return;
#endif
        string prefix = "阿瓦隆已经建好房间，房号:";
        var ret = GUIUtility.systemCopyBuffer = prefix + textRoomId.text;
        if(string.IsNullOrEmpty(ret) || ret == prefix)
            UITips.Instance.Show("不支持拷贝或者房号出错");
        else
            UITips.Instance.Show("已拷贝进剪切板");
        Debug.Log("GUIUtility.systemCopyBuffer:" + ret);
    }

    public void Clear()
    {
        textCotent.text = "";
    }


    public void OnStartBattle(Button button)
    {
        if (!_isRoomHost)
        {
            UITips.Instance.Show(XLocalization.Get("只有房主，才能开始战斗"));
            return;
        }
        WebSocketClient.Instance.SendMsgName(button, "startbattle");
    }

    public void OnExitRoom(Button button)
    {
        WebSocketClient.Instance.SendMsgName(button, "exitroom");
    }
    protected override void onVisible()
    {
        //Facade.Instance.RegistNetEvent(nameof(notify_exitroom), OnHandleNotifyExitroomRsp);//php
        //Facade.Instance.RegistNetEvent(nameof(notify_enterbattle), OnHandleNotifyEnterbattleRsp);//php
        Facade.Instance.RegistNetEvent(nameof(createroom_rsp), OnHandleCreateRoomRsp);//php
        Facade.Instance.RegistNetEvent(nameof(enterroom_rsp), OnHandleEnterRoomRsp);//php
       // Facade.Instance.RegistNetEvent(nameof(notify_enterroom), OnHandleNotifyEnterroomRsp);//php
        //Facade.Instance.RegistNetEvent(nameof(startbattle_rsp), OnHandleStartbattleRsp);//php
        //Facade.Instance.RegistNetEvent(nameof(exitroom_rsp), OnHandleExitRoomRsp);//php
        //Facade.Instance.RegistNetEvent(nameof(reenterroom_rsp), OnHandleReenterroomRsp);//php
        
    }

    protected override void OnInvisible()
    {
        //Facade.Instance.UnRegistNetEvent(nameof(notify_exitroom), OnHandleNotifyExitroomRsp);
        //Facade.Instance.UnRegistNetEvent(nameof(notify_enterbattle), OnHandleNotifyEnterbattleRsp);
        Facade.Instance.UnRegistNetEvent(nameof(createroom_rsp), OnHandleCreateRoomRsp);
        Facade.Instance.UnRegistNetEvent(nameof(enterroom_rsp), OnHandleEnterRoomRsp);//php
        //Facade.Instance.UnRegistNetEvent(nameof(notify_enterroom), OnHandleNotifyEnterroomRsp);
        //Facade.Instance.UnRegistNetEvent(nameof(startbattle_rsp), OnHandleStartbattleRsp);
        //Facade.Instance.UnRegistNetEvent(nameof(exitroom_rsp), OnHandleExitRoomRsp);
        //Facade.Instance.UnRegistNetEvent(nameof(reenterroom_rsp), OnHandleReenterroomRsp);//php
    }

    protected override void OnClose()
    {
        base.OnClose();
        _sequence?.Kill(true);
        _sequence = null;
        Clear();

        buttonClose.gameObject.SetActive(true);
        buttonEnterRoom.gameObject.SetActive(true);
        buttonRandomRoom.gameObject.SetActive(true);
        buttonCreateRoom.gameObject.SetActive(true);
        buttonStartBattle.gameObject.SetActive(false);
        buttonExitRoom.gameObject.SetActive(false);
        //textRoomId.text = "";
    }

    private void OnHandleCreateRoomRsp(System.Object data)
    {
        var rsp = data as createroom_rsp;
        TakeActionRoom(rsp.ret, rsp.reason, rsp.group_id, rsp.member_infos);
    }

    private void OnHandleEnterRoomRsp(System.Object data)
    {
        var rsp = data as enterroom_rsp;
        if(rsp.ret != NetErrorCode.None)
        {
            UITips.Instance.Show(rsp.reason);
            return;
        }
        TakeActionRoom(rsp.ret, rsp.reason, rsp.group_id, rsp.member_infos);
    }

    private void TakeActionRoom(int ret, string reason, string group_id, member_info[] member_infos)
    {

        if (ret != NetErrorCode.None)
        {
            UITips.Instance.Show("出错了:" + reason);
        }
        else
        {
            DataPlayer.Instance.SetGroupId(group_id);

            //缓存group id
            textRoomId.text = group_id;

            //数据保存
            var dataBattle = new DataBattleMgr();
            for (int i = 0; i < member_infos.Length; i++)
            {
                var member = member_infos[i];
                dataBattle.AddDataPlayer(member);
            }
            DataHandle.Instance.dataBattleMgr = dataBattle;

            //进入场景
            SceneMgr.Instance.LoadScene(SceneName.SceneBattle, dataBattle);

            //关闭UI
            this.CloseUI();
        }
    }

    //private void OnHandleNotifyEnterroomRsp(System.Object data)
    //{
    //    var rsp = data as notify_enterroom;
    //    textCotent.text = XLocalization.Get("已匹配人数:") + rsp.num + "/" + MaxRoomNum;
    //}

    //private void OnHandleStartbattleRsp(System.Object data)
    //{
    //    var rsp = data as startbattle_rsp;
    //    if (rsp.ret != NetErrorCode.None)
    //        UITips.Instance.Show("非常抱歉:" + rsp.reason);
    //}

    //private void OnHandleExitRoomRsp(System.Object data)
    //{
    //    var rsp = data as exitroom_rsp;
    //    if (rsp.ret != NetErrorCode.None)
    //    {
    //        UITips.Instance.Show("出错了:" + rsp.reason);
    //        this.OnClose();//恢复状态
    //    }
    //    else
    //    {
    //        this.OnClose();//恢复状态
    //    }
    //    DataPlayer.Instance.ClearGroupId();
    //}

    //private void OnHandleReenterroomRsp(System.Object data)
    //{
    //    var rsp = data as reenterroom_rsp;
    //    if (rsp.ret != NetErrorCode.None)
    //    {
    //        UITips.Instance.Show("出错了:" + rsp.reason);
    //        DataPlayer.Instance.ClearGroupId();
    //     }
    //    else
    //    {

    //    }
    //}

    //private void OnHandleNotifyExitroomRsp(System.Object data)
    //{
    //    var rsp = data as notify_exitroom;
    //    textCotent.text = XLocalization.Get("已匹配人数:") + rsp.num + "/" + MaxRoomNum;
    //}

    //private void OnHandleNotifyEnterbattleRsp(System.Object data)
    //{
    //    var rsp = data as notify_enterbattle;
    //    Debug.Log("收到服务端的notify_enterbattle消息:" + rsp.persons.Length);
    //    this.CloseUI();

    //    //数据保存
    //    var dataBattle = new DataBattleMgr();
    //    for (int i = 0; i < rsp.persons.Length; i++)
    //    {
    //        var person = rsp.persons[i];
    //        //dataBattle.AddDataPlayer(person);
    //    }
    //    dataBattle.ChallengeUid = rsp.challenge_uid;
    //    SceneMgr.Instance.LoadScene(SceneName.SceneBattle, dataBattle);


    //    //var oldGroupId = DataPlayer.Instance.GetGroupId();

    //    //DataPlayer.Instance.ClearGroupId();

   
    //    DataPlayer.Instance.SetGroupId(rsp.group_id);
    //}

    //re enter room
    private void ReEnterRoom()
    {
        //if(!string.IsNullOrEmpty(DataPlayer.Instance.GetGroupId()))
        //{
        //    UIDialog.Instance.Show(XLocalization.Get("提示"), XLocalization.Get("发现旧房间还有人，是否进去？"), () => {
        //        var req = new reenterroom();
        //        req.side = 1;//备用
        //        req.room_id = DataPlayer.Instance.GetGroupId();
        //        WebSocketClient.Instance.SendSerialize(req);
        //        DataPlayer.Instance.ClearGroupId();
        //    }, () => {
        //        //WebSocketClient.Instance.SendMsgName("unbindgroup");
        //        DataPlayer.Instance.ClearGroupId();
        //    });
        //}
        var groupId = DataPlayer.Instance.GetStoreGroupId();
        if (!string.IsNullOrEmpty(groupId))
        {
            textRoomId.text = groupId;
            var hint = "上一次 房号:" + groupId + " 你中途退出了";
            textCotent.text = hint;
            UITips.Instance.Show(hint);

            //播放动画
            var oldPos = buttonEnterRoom.transform.localPosition;
            var newPos = new Vector3(-42, -39, 0);
            buttonEnterRoom.transform.localPosition = newPos;
            Sequence s = DOTween.Sequence(buttonEnterRoom.transform);
            s.Append(buttonEnterRoom.transform.DOLocalMove(oldPos, 0.5f).SetEase(Ease.InSine));;
            s.Append(buttonEnterRoom.transform.DOLocalRotate(new Vector3(0, 0, 90), 0.5f));
            s.Append(buttonEnterRoom.transform.DOLocalRotate(Vector3.zero, 0.5f));
            _sequence = s;
        }
    }
}
